package com.xjh.serverinspect.security.handler;

import com.alibaba.fastjson2.JSON;
import com.xjh.serverinspect.security.JwtHolder;
import com.xjh.serverinspect.security.ResponseBodyHandler;
import com.xjh.serverinspect.util.ResponseDTO;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录成功处理器
 * </p>
 *
 * @author xujinghui
 * @since 2024-12-12
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtHolder jwtHolder;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
        resp.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = resp.getOutputStream();

        // 生成access_token，并放置到请求头中
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", auth.getName());
        String token = jwtHolder.createAccessToken(claims);
        resp.setHeader("Authorization", token);

        outputStream.write(JSON.toJSONBytes(ResponseBodyHandler.encrypt(ResponseDTO.success(token), req)));
        outputStream.flush();
        outputStream.close();
    }
}
